package com.mycirno.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.mycirno.dto.SearchResult;

public class ShowCover extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8147292553431383432L;
	
	private Logger logger = Logger.getLogger(getClass());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		show(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		show(req, resp);
	}
	
	public void show(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String keyword = URLEncoder.encode("一拳超人", "utf-8");
			String page = "0";
			URL url = new URL("http://v2.api.dmzj.com/search/show/0/" + keyword + "/" + page + ".json");
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line = "";
			String html = "";
			while (null != (line = br.readLine())) {
				html += line;
			}
			br.close();
			List<SearchResult> searchResults = strToSearchResult(html);
			resp.setContentType("text/html; charset=utf-8");
			for (SearchResult searchResult : searchResults) {
				String image = searchResult.getCover();
				URL imageUrl = new URL(image);
				HttpURLConnection imageUrlConnection = (HttpURLConnection) imageUrl.openConnection();
				imageUrlConnection.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
				imageUrlConnection.setRequestProperty("Host", "images.dmzj.com");
				imageUrlConnection.setRequestProperty("Referer", "http://m.dmzj.com");
				BufferedImage bi = ImageIO.read(imageUrlConnection.getInputStream());
				ImageIO.write(bi, "JPG", resp.getOutputStream());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public List<SearchResult> strToSearchResult(String html) {
		JSONArray jsonArray = new JSONArray(html);
		List<SearchResult> searchResults = new ArrayList<SearchResult>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			logger.info(jsonObject.getString("cover"));
			SearchResult searchResult = new SearchResult(jsonObject.getLong("id"), jsonObject.getString("status"),
					jsonObject.getString("title"), jsonObject.getString("last_name"), jsonObject.getString("cover"),
					jsonObject.getString("authors"), jsonObject.getLong("hot_hits"));
			searchResults.add(searchResult);
		}
		return searchResults;
	}
	
}
